import { createStore } from 'vuex'
import {setCarListData,getCarListData,setUserDatas,getUSerAsync,getAddress} from '../Tools/toolsSum.js'
const store = createStore({
	state:{
		shoppingCar:getCarListData(),
		userData:getUSerAsync(),
		addressData:getAddress()
	},
	mutations:{
		checkedAll(state){
			if(state.shoppingCar.length > 0){
				state.shoppingCar.forEach(item=>item.isChack = !item.isChack)
			}
		},
		cleanShoppingCar(state,{index,all}){
			if(all){
				state.shoppingCar = []
			}else{
				state.shoppingCar.splice(index,1)
			}
			setCarListData(state.shoppingCar)
		},
		changeShopping(state,value){
			if(state.shoppingCar.every(value=>{
				if(value.goods_id !== value.goods_id){
					return true
				}
				value.goods_count = value.goods_count + 1
			})){
				state.shoppingCar.push(value)
			}
			setCarListData(state.shoppingCar)
		},
		changAttrStatus(state,index){
			if((parseInt(index) + '') !== 'NaN'){
				state.shoppingCar[index] ? state.shoppingCar[index].isChack = !state.shoppingCar[index].isChack : ''
				setCarListData(state.shoppingCar)
				
			}
		},
		addMannyAttrSum(state,{index,num,value}){
			if(String(parseInt(index+num)) !== 'NaN' && !value){
				const sumMain = state.shoppingCar[index].goods_count
				state.shoppingCar[index] ? state.shoppingCar[index].goods_count = sumMain + Number(num) : state.shoppingCar[index].goods_count
			}else{
				state.shoppingCar[index] ? state.shoppingCar[index].goods_count = Number(value) : state.shoppingCar[index].goods_count 
			}
			setCarListData(state.shoppingCar)
		},
		serUserData(state,value){
			
			if(value){
				state.userData = value
				setUserDatas(value)
			}
		}
	},
	getters:{
		sumPirce(state){
			return state.shoppingCar.reduce((_c,value)=>{
				if(value.isChack && value.goods_count){
					return _c + value.goods_price * value.goods_count
				}
				return _c
			},0) 
			
		},
		sumNumAttr(state){
			return state.shoppingCar.reduce((_c,value)=>{
				if(value.isChack && value.goods_count){
					return _c + value.goods_count
				}
				return _c
			},0) 
		},
		isLoing(state){
			return state.userData.errMsg == 'login:ok'
		},
		haveAddress(state){
			return !!state.addressData.provinceName
		}
	}
})

export default store